<template>
  <a-modal
    :visible="visible"
    title="修改虚仿项目"
    cancelText="取消"
    okText="提交"
    @ok="submit"
    @cancel="cancel"
  >
    <a-form
      ref="formRef"
      :model="formState"
      :label-col="labelCol"
      :wrapper-col="wrapperCol">
      <a-form-item ref="emName" label="实验名称" name="emName">
        <a-input v-model:value="formState.emName" />
      </a-form-item>
      <a-form-item ref="departmentName" label="院系名称" name="departmentName">
        <a-input v-model:value="formState.departmentName" />
      </a-form-item>
      <a-form-item label="所属专业类" name="majorStatus">
        <a-tree-select
          v-model:value="formState.majorStatus"
          style="width: 100%"
          :tree-data="state.depts"
          placeholder="所属部门"
          replace
          :replaceFields="replaceFields"
          :disable-branch-nodes="true"
        >
        </a-tree-select>
      </a-form-item>
      <a-form-item label="轮播图" name="enable">
        <a-upload
          name="file"
          v-model="formState.showLargerVersion"
          list-type="picture-card"
          class="avatar-uploader"
          :show-upload-list="false"
          action="http://192.168.0.145:9292/api/sys/upload/uploadFiles"
          :before-upload="beforeUpload"
          @change="handleChange"
          :headers="headers"
        >
          <img v-if="imageUrl" :src="imageUrl" alt="avatar" style="width: 100%" />
          <div v-else>
            <loading-outlined v-if="loading"></loading-outlined>
            <plus-outlined v-else></plus-outlined>
            <div class="ant-upload-text">请上传1920*420像素的图片</div>
          </div>
        </a-upload>
      </a-form-item>
      <a-form-item label="展示封面" name="enable">
        <a-upload
          name="file"
          v-model="formState.surfacePlot"
          list-type="picture-card"
          class="avatar-uploader1"
          :show-upload-list="false"
          action="http://192.168.0.145:9292/api/sys/upload/uploadFiles"
          :before-upload="beforeUpload"
          @change="handleChange1"
          :headers="headers"
        >
          <img v-if="imageUrl1" :src="imageUrl1" alt="avatar" width="110" height="110" />
          <div v-else>
            <loading-outlined v-if="loading"></loading-outlined>
            <plus-outlined v-else></plus-outlined>
            <div class="ant-upload-text">Upload</div>
          </div>
        </a-upload>
      </a-form-item>
      <a-form-item ref="webglAddress" label="虚仿地址" name="webglAddress">
        <a-input v-model:value="formState.webglAddress" />
      </a-form-item>
      <a-form-item ref="brief" label="项目概要" name="brief">
        <a-input v-model:value="formState.brief" />
      </a-form-item>
      <a-form-item label="项目简介" name="description">
        <!--        <a-textarea v-model:value="formState.description" />-->
        <BasicEditor v-if="visible" ref="header" :record="valueHtml"></BasicEditor>
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script>
import { message } from 'ant-design-vue';
import { edit } from "@/api/module/inbox";
import { defineComponent, reactive, ref, toRaw, watch } from "vue";
import {LoadingOutlined, PlusOutlined} from "_@ant-design_icons-vue@6.1.0@@ant-design/icons-vue";
import BasicEditor from "@/view/components/BasicEditor";
import {eicEdit, tree} from "@/api/module/experiment";

function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}

export default defineComponent({
  components:{
    LoadingOutlined,
    PlusOutlined,
    BasicEditor,
  },
  props: {
    visible: {
      type: Boolean,
    },
    record: {
      type: Object,
    }
  },
  data() {
    return {

    }
  },
  emit: ["close"],
  setup(props, context) {

    const formRef = ref();
    const valueHtml = ref();
    const  show = ref(true);

    const formState = reactive({
      surfacePlot:"",
      showLargerVersion:"",
    });
    watch(props, (props) => {
        formState.id = props.record.id
        formState.brief = props.record.brief
        formState.createName = props.record.createName
        formState.createTime = props.record.createTime
        formState.departmentName = props.record.departmentName
        formState.description = props.record.description
        formState.emName = props.record.emName
        formState.major = props.record.major
        formState.majorStatus = props.record.majorStatus
        formState.webglAddress = props.record.webglAddress
        imageUrl.value = props.record.showLargerVersion
        imageUrl1.value = props.record.surfacePlot
        valueHtml.value = props.record.description
    })

    const formRules = {
    };

    const editKey = "edit";
    const submit = (e) => {
      formState.description = toRaw(header.value.aaa)
      console.log(JSON.stringify(toRaw(formState)));
      formRef.value
        .validate()
        .then(() => {
          eicEdit(toRaw(formState)).then((response)=>{
              if(response.success){
                message.success({ content: '保存成功',  editKey, duration: 1 }).then(()=>{
                  cancel();
                });
              }else{
                message.success({ content: '保存失败',  editKey, duration: 1 }).then(()=>{
                  cancel();
                });
              }
          });
        })
        .catch(error => {
          console.log('error', error);
        });
    };

    const cancel = (e) => {
      formRef.value.resetFields();
      context.emit("close", false);
    };

    const loading = ref(false);
    const loading1 = ref(false);
    const imageUrl = ref('');
    const imageUrl1 = ref('');
    const header = ref(null);

    const state = reactive({
      posts: [],
      depts: [],
    })

    const loadTree = () => {
      tree({}).then((response)=>{
        state.depts = response.data;
      })
    }
    /// 加载专业分类树
    loadTree();

    // 上传头像改变时的状态
    const handleChange = info => {
      if (info.file.status === 'uploading') {
        loading.value = true;
        return;
      }

      if (info.file.status === 'done') {
        getBase64(info.file.originFileObj, base64Url => {
          imageUrl.value = base64Url;
          loading.value = false;
          console.log("图片url：",info.file.response.data.url)
          if(info.file.response.code === 200){
            formState.showLargerVersion = info.file.response.data.url
            message.success("上传成功")
          }
        });
      }

      if (info.file.status === 'error') {
        loading.value = false;
        message.error('upload error');
      }
    };
    const handleChange1 = info => {
      if (info.file.status === 'uploading') {
        loading1.value = true;
        return;
      }

      if (info.file.status === 'done') {
        getBase64(info.file.originFileObj, base64Url => {
          imageUrl1.value = base64Url;
          loading1.value = false;
          console.log("图片1url：",info.file.response.data.url)
          if(info.file.response.code === 200){
            formState.surfacePlot = info.file.response.data.url
            message.success("上传成功")
          }
        });
      }

      if (info.file.status === 'error') {
        loading1.value = false;
        message.error('upload error');
      }
    };
    // 上传文件之前的钩子
    const beforeUpload = file => {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';

      if (!isJpgOrPng) {
        message.error('只能上传【png/jpg】格式图片！');
      }
      const isLt2M = file.size / 1024 / 1024 < 100;
      if (!isLt2M) {
        message.error('图片大小不能超过【100MB】!');
      }
      return isJpgOrPng && isLt2M;
    };
    // 上传图片携带token
    const tokenKey = localStorage.getItem("token_key");
    const token = localStorage.getItem("token")

    const headers = {
      "Authorization": token,
      "Authorization-key": tokenKey
    };

    return {
      submit,
      cancel,
      valueHtml,
      formRef,
      formState,
      formRules,

      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
      state,

      replaceFields: {children:'children', title:'maName', key:'id', value: 'id' },
      // 下面是上传图片所用接口
      loading,
      loading1,
      imageUrl,
      imageUrl1,
      handleChange,
      handleChange1,
      beforeUpload,
      headers,
      header,
      show,
    };
  },
});
</script>
